package
{
	import flash.events.AsyncErrorEvent;
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.events.IOErrorEvent;
	import flash.events.NetStatusEvent;
	import flash.net.NetConnection;
	
	import mx.controls.Alert;
	import mx.utils.ObjectUtil;
	
	public class NetConnection2
	{
		public var nc:NetConnection;
		public var url:String;
		public var encoding:uint;
		public var dispatcher:EventDispatcher = new EventDispatcher(null);
		
		public static const CONNECTED_EVENT:String = "connected_event";
		public static const DISCONNECTED_EVENT:String = "disconnected_event";
		public static const UNKNOWN_EVENT:String = "unknown_event";
		
		public function NetConnection2()
		{
			nc = new NetConnection();	
		}
		
		public function connect():void {
			
			nc.objectEncoding = encoding;
			nc.addEventListener(NetStatusEvent.NET_STATUS, netStatusEventHandler);
			nc.addEventListener(AsyncErrorEvent.ASYNC_ERROR, netAsync);
			nc.addEventListener(IOErrorEvent.IO_ERROR, netIO);
			nc.client = this;
			nc.connect(url);
		}
		
		public function get connected():Boolean {
			if (nc) {
				return nc.connected;
			} else {
				return false;
			}
		}
		
		public function netAsync(e:AsyncErrorEvent):void {
			trace(ObjectUtil.toString(e));
		}
		
		public function netIO(e:IOErrorEvent):void {
			trace(ObjectUtil.toString(e));
		}		
		
		public function netStatusEventHandler(e:NetStatusEvent):void {
			switch (e.info.code) {
				case "NetConnection.Connect.Success": { 
					dispatcher.dispatchEvent(new Event(CONNECTED_EVENT)); 
					break;
				}
				case "NetConnection.Connect.Rejected": {
					dispatcher.dispatchEvent(new Event(DISCONNECTED_EVENT));
					break;
				}
				case "NetConnection.Connect.Failed": { 
					dispatcher.dispatchEvent(new Event(DISCONNECTED_EVENT)); 
					break;
				}
				case "NetConnection.Connect.Closed": { 
					dispatcher.dispatchEvent(new Event(DISCONNECTED_EVENT)); 
					break;
				}
				default: {
					trace("netStatusEventHandler: " + e.info.code);
					dispatcher.dispatchEvent(new Event(UNKNOWN_EVENT));
					break;
				}
			}
		}
		
		public function onBWDone():void {
			
		}
		
	}
}